package org.nanquan.dotjava.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializationObject implements Serializable {
	
	String encoding="iso8859-1";
	/**
	 * 
	 */
	private static final long serialVersionUID = -1447171023877594486L;
	
	public SerializationObject(){}
	
	public SerializationObject(String encoding)
	{
		this.encoding=encoding;
	}

	public synchronized byte[] saveObject(Serializable obj) throws IOException {
		ByteArrayOutputStream byteoutstream=new ByteArrayOutputStream();
		ObjectOutputStream out=new ObjectOutputStream(byteoutstream);
		out.writeObject(obj);
		return byteoutstream.toByteArray();
	}
	
	public synchronized String saveObjectToHexString(Serializable obj) throws IOException
	{
		return ConvertUtil.bytesToHexString(saveObject(obj));
	}
	
	//public synchronized 
	
	public synchronized String saveObjectToString(Serializable obj,String encoding) throws IOException {
		return new String(saveObject(obj),encoding);
	}
	
	public synchronized String saveObjectToString(Serializable obj) throws IOException {
		return saveObjectToString(obj,this.encoding);
	}
	
	public synchronized Object getObject(byte [] objbytes) throws IOException, ClassNotFoundException
	{
		ByteArrayInputStream bytestream = new ByteArrayInputStream(objbytes);
		ObjectInputStream in = new ObjectInputStream(bytestream);
		return in.readObject();
	}
	
	public synchronized Object getObject(String objstr,String encoding) throws IOException, ClassNotFoundException
	{
		byte [] bytes=objstr.getBytes(encoding);
		return getObject(bytes);
	}
	public synchronized Object getObject(String objstr) throws IOException, ClassNotFoundException
	{
		return getObject(objstr,this.encoding);
	}
	
	

}
